package com.imooc.miaoshaproject.service.impl;

import com.imooc.miaoshaproject.mapper.OrderDOMapper;
import com.imooc.miaoshaproject.po.SequencePO;
import com.imooc.miaoshaproject.exceptions.ServiceException;
import com.imooc.miaoshaproject.exceptions.ErrorCodeEnum;
import com.imooc.miaoshaproject.service.ItemService;
import com.imooc.miaoshaproject.service.OrderService;
import com.imooc.miaoshaproject.service.UserService;
import com.imooc.miaoshaproject.service.model.ItemModel;
import com.imooc.miaoshaproject.service.model.OrderModel;
import com.imooc.miaoshaproject.service.model.UserModel;
import com.imooc.miaoshaproject.mapper.SequenceDOMapper;
import com.imooc.miaoshaproject.po.OrderPO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class OrderServiceImpl implements OrderService {

    private final SequenceDOMapper sequenceDOMapper;

    private final ItemService itemService;

    private final UserService userService;

    private final OrderDOMapper orderDOMapper;

    public OrderServiceImpl(OrderDOMapper orderDOMapper, SequenceDOMapper sequenceDOMapper, ItemService itemService, UserService userService) {
        this.orderDOMapper = orderDOMapper;
        this.sequenceDOMapper = sequenceDOMapper;
        this.itemService = itemService;
        this.userService = userService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderModel createOrder(Integer userId, Integer itemId, Integer promoId, Integer amount) throws ServiceException {
        //1.校验下单状态,下单的商品是否存在，用户是否合法，购买数量是否正确
        ItemModel itemModel = itemService.getItemById(itemId);
        if(itemModel == null){
            throw new ServiceException(ErrorCodeEnum.PARAMETER_VALIDATION_ERROR,"商品信息不存在");
        }

        UserModel userModel = userService.getUserById(userId);
        if(userModel == null){
            throw new ServiceException(ErrorCodeEnum.PARAMETER_VALIDATION_ERROR,"用户信息不存在");
        }
        if(amount <= 0 || amount > 99){
            throw new ServiceException(ErrorCodeEnum.PARAMETER_VALIDATION_ERROR,"数量信息不正确");
        }

        //校验活动信息
        if(promoId != null){
            if(promoId.intValue() != itemModel.getPromoModel().getId()){
                throw new ServiceException(ErrorCodeEnum.PARAMETER_VALIDATION_ERROR,"活动信息不正确");
                //2:进行中
            }else if(itemModel.getPromoModel().getStatus() != 2) {
                throw new ServiceException(ErrorCodeEnum.PARAMETER_VALIDATION_ERROR,"活动信息还未开始");
            }
        }

        //2.落单减库存
        boolean result = itemService.decreaseStock(itemId,amount);
        if(!result){
            throw new ServiceException(ErrorCodeEnum.STOCK_NOT_ENOUGH);
        }

        //3.订单入库
        OrderModel orderModel = new OrderModel();
        orderModel.setUserId(userId);
        orderModel.setItemId(itemId);
        orderModel.setAmount(amount);
        if(promoId != null){
            orderModel.setItemPrice(itemModel.getPromoModel().getPromoItemPrice());
        }else{
            orderModel.setItemPrice(itemModel.getPrice());
        }
        orderModel.setPromoId(promoId);
        orderModel.setOrderPrice(orderModel.getItemPrice().multiply(new BigDecimal(amount)));

        //生成交易流水号,订单号
        orderModel.setId(generateOrderNo());
        OrderPO orderPO = convertFromOrderModel(orderModel);
        orderDOMapper.insertSelective(orderPO);

        //加上商品的销量
        itemService.increaseSales(itemId,amount);
        //4.返回前端
        return orderModel;
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String generateOrderNo(){
        //订单号有16位
        StringBuilder stringBuilder = new StringBuilder();
        //前8位为时间信息，年月日
        LocalDateTime now = LocalDateTime.now();
        String nowDate = now.format(DateTimeFormatter.ISO_DATE).replace("-","");
        stringBuilder.append(nowDate);

        //中间6位为自增序列
        //获取当前sequence
        int sequence = 0;
        SequencePO sequencePO =  sequenceDOMapper.getSequenceByName("order_info");
        sequence = sequencePO.getCurrentValue();
        sequencePO.setCurrentValue(sequencePO.getCurrentValue() + sequencePO.getStep());
        sequenceDOMapper.updateByPrimaryKeySelective(sequencePO);
        String sequenceStr = String.valueOf(sequence);
        for(int i = 0; i < 6-sequenceStr.length();i++){
            stringBuilder.append(0);
        }
        stringBuilder.append(sequenceStr);
        //最后2位为分库分表位,暂时写死
        stringBuilder.append("00");
        return stringBuilder.toString();
    }

    private OrderPO convertFromOrderModel(OrderModel orderModel){
        if(orderModel == null){
            return null;
        }
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderModel, orderPO);
        orderPO.setItemPrice(orderModel.getItemPrice().doubleValue());
        orderPO.setOrderPrice(orderModel.getOrderPrice().doubleValue());
        return orderPO;
    }
}
